package cn.edu.zafu.demo.ui.presenter;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;

import cn.edu.zafu.demo.api.Listener;
import cn.edu.zafu.demo.api.LoginApi;
import cn.edu.zafu.demo.ui.view.LoginView;

/**
 * @author lizhangqu
 * @since 2016-02-21 10:31
 */
public class LoginPresenter extends MvpBasePresenter<LoginView> {

    public void login(final String username, final String password) {
        if (username == null || username.equals("")) {
            LoginView view = getView();
            if (view != null) {
                view.onLoginFailure(LoginView.USERNAME_OR_PASSWORD_EMPTY);
                return;
            }
        } else if (password == null || password.equals("")) {
            LoginView view = getView();
            if (view != null) {
                view.onLoginFailure(LoginView.USERNAME_OR_PASSWORD_EMPTY);
                return;
            }
        }
        Listener<String> listener = new Listener<String>() {
            @Override
            public void onSuccess(String str) {
                LoginView view = getView();
                if (view != null) {
                    view.onLoginSuccess();
                }
            }

            @Override
            public void onFailure(int code) {
                if (code == LoginView.USERNAME_OR_PASSWORD_ERROR) {
                    LoginView view = getView();
                    if (view != null) {
                        view.onLoginFailure(LoginView.USERNAME_OR_PASSWORD_ERROR);
                    }
                } else {
                    LoginView view = getView();
                    if (view != null) {
                        view.onLoginFailure(LoginView.SERVER_ERROR);
                    }
                }
            }
        };
        LoginApi.login(username, password, listener);
    }
}
